#include <iostream>
#include <vector>

using namespace std;
class Solution {
public:
    const int INF = 0x3f3f3f3f;
    int maxProfit(int k, vector<int>& p) {
        int n = p.size();
        vector<vector<int>> f(n, vector<int>(k + 1, -INF));
        vector<vector<int>> g(n, vector<int>(k + 1, -INF));
        g[0][0] = -p[0];
        f[0][0] = 0;

        for (int i = 1; i < n; ++i)
        {
            for (int j = 0; j <= k; ++j)
            {
                g[i][j] = max(g[i - 1][j], f[i - 1][j] - p[i]);
                if (j >= 1)
                    f[i][j] = max(f[i - 1][j], g[i - 1][j - 1] + p[i]);
                else
                    f[i][j] = f[i - 1][j];
            }
        }
        int ret = 0;
        for (int j = 0; j <= k; ++j)
        {
            if (ret < f[n - 1][j])
                ret = f[n - 1][j];
        }
        return ret;
    }
};